﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FantastPlatform.Framework;
using FantastPlatform.Framework.Core;
using FantastPlatform.Framework.Model;
using FantastPlatform.Decision.IService;
using FantastPlatform.Decision.IModel;
using FantastPlatform.Decision.Model;
using FantastPlatform.Framework.IService;
using FantastPlatform.Framework.IModel;

namespace FantastPlatform.Decision.UI.Service
{
    public partial class FlowElementViewService : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginEmployee = Session["User"] as FantastPlatform.Framework.Model.Employee;
            IFlowElementService flowElementService = ServiceFactory.CreateService<IFlowElementService>();
            IFlowLevelService flowLevelService = ServiceFactory.CreateService<IFlowLevelService>();
            ConditionGroup group = new ConditionGroup();
            Condition enableCondition = new Condition() { Type = typeof(bool).FullName, Field = "Enable", Value1 = true };
            group.Conditions.Add(enableCondition);
            int flowId = 0;
            int totalCount = 0;
            string level = "0";
            switch (Action)
            {
                case "Add":
                    if (!string.IsNullOrEmpty(Request["flowId"]))
                    {
                        flowId = Int32.Parse(Request["flowId"]);
                    }
                    if (!string.IsNullOrEmpty(Request["level"]))
                    {
                        level = Request["level"];
                    }
                    if (level == "0")
                    {
                        ReturnErrorMessage("请选择级别");
                        return;
                    }
                    string data = Data;
                    IFlowElement flowElement = (IFlowElement)JsonToEntity<FlowElement>(RepairString(data));
                    // GetLeaders(flowElement);
                    if (flowElement.Id == 0)
                    {
                        flowElement.Enable = true;
                        flowElement.CreateDate = DateTime.Now;
                        if (flowId != 0)
                        {
                            flowElement.FlowFile = new FlowFile() { Id = flowId };
                        }
                        flowElement.Level = level;
                        flowElementService.Create(flowElement);
                        ReturnSuccessMessage("保存警力分配成功");
                    }
                    else
                    {
                        IFlowElement OldMaintainStability = flowElementService.Get(flowElement.Id);
                        OldMaintainStability.ModifyDate = DateTime.Now;
                        OldMaintainStability.Name = flowElement.Name;
                        OldMaintainStability.Organization = flowElement.Organization;
                        OldMaintainStability.PersonNumber = flowElement.PersonNumber;
                        OldMaintainStability.Require = flowElement.Require;
                        OldMaintainStability.Equip = flowElement.Equip;
                        flowElementService.Update(OldMaintainStability);
                        ReturnSuccessMessage("更新警力分配成功");
                    }
                    break;
                case "AddElementImplement":
                    if (!string.IsNullOrEmpty(Request["flowId"]))
                    {
                        flowId = Int32.Parse(Request["flowId"]);
                    }
                    IElementImplementService implementServcie = ServiceFactory.CreateService<IElementImplementService>();
                    IElementImplement elementImplement = (IElementImplement)JsonToEntity<ElementImplement>(RepairString(Data));
                    // GetLeaders(flowElement);
                    if (elementImplement.Id == 0)
                    {
                        elementImplement.Enable = true;
                        elementImplement.CreateDate = DateTime.Now;
                        if (flowId != 0)
                        {
                            elementImplement.FlowImplement = new FlowImplement() { Id = flowId };
                        }
                        implementServcie.Create(elementImplement);
                        ReturnSuccessMessage("保存警力分配成功");
                    }
                    else
                    {
                        IElementImplement OldItem = implementServcie.Get(elementImplement.Id);
                        OldItem.ModifyDate = DateTime.Now;
                        OldItem.Organization = elementImplement.Organization;
                        OldItem.PersonNumber = elementImplement.PersonNumber;
                        OldItem.Require = elementImplement.Require;
                        OldItem.StatusInfo = elementImplement.StatusInfo;
                        OldItem.StartTime = elementImplement.StartTime;
                        OldItem.EndTime = elementImplement.EndTime;
                        OldItem.Description = elementImplement.Description;
                        OldItem.Equip = elementImplement.Equip;
                        implementServcie.Update(OldItem);
                        ReturnSuccessMessage("更新警力分配成功");
                    }
                    break;
                case "AddLevelRange":
                    if (!string.IsNullOrEmpty(Request["flowId"]))
                    {
                        flowId = Int32.Parse(Request["flowId"]);
                    }
                    if (!string.IsNullOrEmpty(Request["flowId"]))
                    {
                        level = Request["level"];
                    }
                    group.Conditions.Add(new Condition() { Field = "FlowFile.Id", Type = typeof(int).FullName, Relation = Relations.And, Value1 = flowId });
                    group.Conditions.Add(new Condition() { Field = "Level", Type = typeof(string).FullName, Relation = Relations.And, Value1 = level });

                    IList<IFlowLevel> flowLevelList = flowLevelService.Search(group, null, int.MaxValue, 1, out totalCount);
                    if (totalCount == 0)
                    {
                        IFlowLevel flowLevel = new FlowLevel();
                        flowLevel.Level = level;
                        if (!string.IsNullOrEmpty(Request["Range"]))
                        {
                            flowLevel.Description = Request["Range"];
                        }
                        if (!string.IsNullOrEmpty(Request["personNumber"]))
                        {
                            flowLevel.PersonNumber = Request["personNumber"];
                        }
                        flowLevel.CreateDate = DateTime.Now;
                        if (flowId != 0)
                        {
                            flowLevel.FlowFile = new FlowFile() { Id = flowId };
                        }
                        flowLevelService.Create(flowLevel);
                        ReturnSuccessMessage("保存预案级别描述成功");
                    }
                    else
                    {

                        IFlowLevel OldFlowLevel = flowLevelService.Get(flowLevelList[0].Id);
                        OldFlowLevel.ModifyDate = DateTime.Now;
                        if (!string.IsNullOrEmpty(Request["Range"]))
                        {
                            OldFlowLevel.Description = Request["Range"];
                        }
                        if (!string.IsNullOrEmpty(Request["personNumber"]))
                        {
                            OldFlowLevel.PersonNumber = Request["personNumber"];
                        }
                        flowLevelService.Update(OldFlowLevel);
                        ReturnSuccessMessage("更新预案级别描述成功");
                    }
                    break;
                case "Search":
                    if (!string.IsNullOrEmpty(Request["flowId"]))
                    {
                        flowId = Int32.Parse(Request["flowId"]);
                    }
                    if (!string.IsNullOrEmpty(Request["level"]))
                    {
                        level = Request["level"];
                    }
                    group.Conditions.Add(new Condition() { Field = "FlowFile.Id", Type = typeof(int).FullName, Relation = Relations.And, Value1 = flowId });
                    group.Conditions.Add(new Condition() { Field = "Level", Type = typeof(string).FullName, Relation = Relations.And, Value1 = level });

                    IList<Sort> sorts = new List<Sort>();
                    sorts.Add(new Sort() { Field = "CreateDate", Order = Orders.Asc });
                    IList<IFlowElement> flowElementList = flowElementService.Search(group, sorts, PageSize, SelfPage, out totalCount);
                    var obj = from n in flowElementList
                              select new
                              {
                                  Id = n.Id,
                                  Organization = n.Organization,
                                  PersonNumber = n.PersonNumber,
                                  Details = n.Details,
                                  EchelonNumber = n.EchelonNumber

                              };
                    ReturnList(totalCount, obj.ToList());
                    break;
                case "SearchByCondition":
                    if (!string.IsNullOrEmpty(Request["flowId"]))
                    {
                        flowId = Int32.Parse(Request["flowId"]);
                    }                  
                    group.Conditions.Add(new Condition() { Field = "FlowFile.Id", Type = typeof(int).FullName, Relation = Relations.And, Value1 = flowId });
                    group.Conditions.Add(new Condition() { Field = "Level", Type = typeof(string).FullName, Relation = Relations.And, Value1 = Id });
                    group.Conditions.Add(new Condition() { Field = "Organization", Type = typeof(string).FullName, Relation = Relations.And, Value1 = "%"+Data+"%",Comparison= Comparisons.Like });

                    sorts = new List<Sort>();
                    sorts.Add(new Sort() { Field = "CreateDate", Order = Orders.Asc });
                    flowElementList = flowElementService.Search(group, sorts, PageSize, SelfPage, out totalCount);
                    obj = from n in flowElementList
                          select new
                          {
                              Id = n.Id,
                              Organization = n.Organization,
                              PersonNumber = n.PersonNumber,
                              Details = n.Details,
                              EchelonNumber = n.EchelonNumber

                          };
                    ReturnList(totalCount, obj.ToList());
                    break;
                case "Get":
                    flowElement = flowElementService.Get(Id);
                    object objFlowFile = (new
                                     {
                                         Name = flowElement.Name,
                                         Organization = flowElement.Organization,
                                         EchelonNumber = flowElement.EchelonNumber,
                                         PersonNumber = flowElement.PersonNumber,
                                         Require = flowElement.Require,
                                         Equip = flowElement.Equip,
                                         Details = flowElement.Details
                                     });
                    ReturnObj(objFlowFile);
                    break;
                case "GetElementImplement":
                    implementServcie = ServiceFactory.CreateService<IElementImplementService>();
                    elementImplement = implementServcie.Get(Id);
                    object objImplement = (new
                                     {
                                         Organization = elementImplement.Organization,
                                         Description = elementImplement.Description,
                                         EchelonNumber = elementImplement.EchelonNumber,
                                         PersonNumber = elementImplement.PersonNumber,
                                         Require = elementImplement.Require,
                                         StartTime = elementImplement.StartTime,
                                         EndTime = elementImplement.EndTime,
                                         StatusInfo = elementImplement.StatusInfo,
                                         Equip = elementImplement.Equip,
                                         Details = elementImplement.Details
                                     });
                    ReturnObj2(objImplement);
                    break;
                case "GetLevelInfo":
                    if (!string.IsNullOrEmpty(Request["flowId"]))
                    {
                        flowId = Int32.Parse(Request["flowId"]);
                    }
                    if (!string.IsNullOrEmpty(Request["flowId"]))
                    {
                        level = Request["level"];
                    }
                    group.Conditions.Add(new Condition() { Field = "FlowFile.Id", Type = typeof(int).FullName, Relation = Relations.And, Value1 = flowId });
                    group.Conditions.Add(new Condition() { Field = "Level", Type = typeof(string).FullName, Relation = Relations.And, Value1 = level });
                    flowLevelService = ServiceFactory.CreateService<IFlowLevelService>();
                    flowLevelList = flowLevelService.Search(group, null, int.MaxValue, 1, out totalCount);
                    if (totalCount > 0)
                    {
                        object levelObj = new { Range = flowLevelList[0].Description, PersonNumber = flowLevelList[0].PersonNumber };
                        ReturnObj(levelObj);
                    }
                    else
                    {
                        object levelObj = new { Range = "", PersonNumber = "" };
                        ReturnObj(levelObj);
                    }
                    break;
                case "Delete":
                    if (string.IsNullOrEmpty(Data))
                    {
                        throw new Exception("传入的警力分布ID为空");
                    }
                    List<int> idList = new List<int>();
                    string[] idStrList = Data.Split(',');
                    foreach (string id in idStrList)
                    {
                        idList.Add(int.Parse(id));
                    }
                    flowElementService.Delete(idList);
                    ReturnSuccessMessage("删除警力分布成功");
                    break;
                case "SearchLevelByFlowId":
                    if (!string.IsNullOrEmpty(Request["flowId"]))
                    {
                        flowId = Int32.Parse(Request["flowId"]);
                    }
                    sorts = new List<Sort>();
                    sorts.Add(new Sort() { Field = "Level", Order = Orders.Asc });
                    group.Conditions.Add(new Condition() { Field = "FlowFile.Id", Type = typeof(int).FullName, Value1 = flowId, Relation = Relations.And });

                    IList<IFlowLevel> levelList = flowLevelService.Search(group, sorts, PageSize, SelfPage, out totalCount);
                    var objLevel = from n in levelList
                                   where n.Enable == true
                                   select new
                                   {
                                       Id = n.Id,
                                       Name = GetLeveName(n.Level),
                                       Description = n.Description
                                   };
                    ReturnList(objLevel.Count(), objLevel.ToList());
                    break;
                case "SearchImplement":
                    if (!string.IsNullOrEmpty(Request["flowId"]))
                    {
                        flowId = Int32.Parse(Request["flowId"]);
                    }
                    // sorts = new List<Sort>();
                    //sorts.Add(new Sort() { Field = "Level", Order = Orders.Asc });
                    group.Conditions.Add(new Condition() { Field = "FlowImplement.Id", Type = typeof(int).FullName, Value1 = flowId, Relation = Relations.And });
                    IElementImplementService elementImplementService = ServiceFactory.CreateService<IElementImplementService>();
                    IList<IElementImplement> implementList = elementImplementService.Search(group, null, PageSize, SelfPage, out totalCount);
                    var objLevel2 = from n in implementList
                                    where n.Enable == true
                                    select new
                                    {
                                        Id = n.Id,
                                        OrgRange = !string.IsNullOrEmpty(n.Organization) ? n.Organization : "",
                                        Details = !string.IsNullOrEmpty(n.Details) ? n.Details : "",
                                        Equip = !string.IsNullOrEmpty(n.Equip) ? n.Equip : "",
                                        Require = !string.IsNullOrEmpty(n.Require) ? n.Require : "",
                                        PersonNumber = !string.IsNullOrEmpty(n.PersonNumber) ? n.PersonNumber : "",
                                        EchelonNumber = !string.IsNullOrEmpty(n.EchelonNumber) ? n.EchelonNumber : "",
                                        StartTime = n.StartTime != null ? n.StartTime.ToString() : "",
                                        EndTime = n.EndTime != null ? n.EndTime.ToString() : "",
                                        Status = n.StatusInfo != null ? n.StatusInfo.ToString() : "",
                                        Description = !string.IsNullOrEmpty(n.Description) ? n.Description : ""
                                    };
                    ReturnList(objLevel2.Count(), objLevel2.ToList());
                    break;
                case "SearchImplementByCondition":

                    group.Conditions.Add(new Condition() { Field = "FlowImplement.Id", Type = typeof(int).FullName, Value1 = Id, Relation = Relations.And });
                    group.Conditions.Add(new Condition() { Field = "Organization", Type = typeof(string).FullName, Value1 = "%" + Data + "%", Relation = Relations.And, Comparison = Comparisons.Like });

                    elementImplementService = ServiceFactory.CreateService<IElementImplementService>();
                    implementList = elementImplementService.Search(group, null, PageSize, SelfPage, out totalCount);
                    objLevel2 = from n in implementList
                                where n.Enable == true
                                select new
                                {
                                    Id = n.Id,
                                    OrgRange = !string.IsNullOrEmpty(n.Organization) ? n.Organization : "",
                                    Details = !string.IsNullOrEmpty(n.Details) ? n.Details : "",
                                    Equip = !string.IsNullOrEmpty(n.Equip) ? n.Equip : "",
                                    Require = !string.IsNullOrEmpty(n.Require) ? n.Require : "",
                                    PersonNumber = !string.IsNullOrEmpty(n.PersonNumber) ? n.PersonNumber : "",
                                    EchelonNumber = !string.IsNullOrEmpty(n.EchelonNumber) ? n.EchelonNumber : "",
                                    StartTime = n.StartTime != null ? n.StartTime.ToString() : "",
                                    EndTime = n.EndTime != null ? n.EndTime.ToString() : "",
                                    Status = n.StatusInfo != null ? n.StatusInfo.ToString() : "",
                                    Description = !string.IsNullOrEmpty(n.Description) ? n.Description : ""
                                };
                    ReturnList(objLevel2.Count(), objLevel2.ToList());
                    break;

            }
        }

        private string GetLeveName(string p)
        {
            string levelName = "";
            switch (p)
            {
                case "1": levelName = "A级加强";
                    break;
                case "2": levelName = "A级";
                    break;
                case "3": levelName = "B级";
                    break;
                case "4": levelName = "C级";
                    break;
                case "5": levelName = "D级";
                    break;
            }
            return levelName;
        }
    }
}